package com.tongjie.hotelbooking.user.service;

import com.tongjie.hotelbooking.dto.LoginRequest;
import com.tongjie.hotelbooking.user.entity.User;
import com.tongjie.hotelbooking.user.enums.UserStatus;
import com.tongjie.hotelbooking.user.enums.UserType;
import com.tongjie.hotelbooking.user.repository.UserRepository;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;

@Service
public class UserService {

    @Resource
    private UserRepository userRepository;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Transactional
    public void register(LoginRequest dto, String ip) {
        User user = User.builder()
                .mobile(dto.getMobile())
                .wxOpenId(dto.getWxOpenId())
                .username(dto.getMobile())
                .password(dto.getMobile())
                .userType(dto.getUserType())
                .userStatus(UserStatus.ACTIVITED)
                .avatar(dto.getAvatar())
                .nickName(dto.getNickName())
                .lastLoginIp(ip)
                .registerIp(ip)
                .registerTime(new Date())
                .lastLoginTime(new Date())
                .createTime(new Date())
                .uuid(UUID.randomUUID().toString())
                .build();
        this.userRepository.save(user);
    }

    @Transactional
    public void updateUser(User user) {
        this.userRepository.save(user);
    }

    public User getUserByUsername(String username) {
        return this.userRepository.getUserByUsername(username);
    }

    public User getUserByWxOpenId(String wxOpenId) {
        return this.userRepository.getUserByWxOpenId(wxOpenId);
    }

    public User getUserByMobile(String mobile) {
        return this.userRepository.getUserByMobile(mobile);
    }

    public User getUserById(Long userId) {
        return this.userRepository.findById(userId).orElse(null);
    }

    public Page<User> findUser(Example<User> example, Pageable pageable) {
        return this.userRepository.findAll(example, pageable);
    }
}
